package com.itany.corejava.code16_反射;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author MissChen
 * @date 2024年03月26日 15:09
 */
public class Test05_Method {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class c = User.class;
        // 1.获取当前类以及其祖先类中所有public修饰的方法
        Method[] methods = c.getMethods();
        System.out.println(Arrays.toString(methods));

        // 2.获取当前类中所有方法,不区分修饰符
        Method[] declaredMethods = c.getDeclaredMethods();
        System.out.println(Arrays.toString(declaredMethods));

        // 3.获取当前类以及其祖先类中指定参数的public修饰的方法
        // getMethod("方法名", Class<?>... parameterTypes)

        Method sumMethod = c.getMethod("sum", double.class, double.class);
        System.out.println(sumMethod);

        Method addMethod = c.getMethod("add", int.class, int.class);
        System.out.println(addMethod);

        //无法访问private修饰的方法
        // Method add2Method=c.getMethod("add2",int.class,int.class);
        // System.out.println(add2Method);

        // 4.获取当前类中任意方法,不区分修饰符
        // getDeclaredMethod(String name, Class<?>... parameterTypes)
        Method reduce = c.getDeclaredMethod("reduce", double.class, double.class);
        System.out.println(reduce);

        //无法访问父类方法
        // Method add=c.getDeclaredMethod("add",int.class,int.class);
        // System.out.println(add);

        //获取方法名
        System.out.println(addMethod.getName());
        System.out.println(reduce.getName());

        User user = new User();
        // Method对象.invoke(方法所在的对象是谁, Object... args)
        double sum = (double) sumMethod.invoke(user, 10, 20);
        System.out.println(sum);

        // 无法调用private修饰的方法，需要取消权限控制检查
        reduce.setAccessible(true);
        double res = (double) reduce.invoke(user, 20, 30);
        System.out.println(res);
    }
}
